const svgCaptcha = require('svg-captcha');
const sm4 = require('sm-crypto').sm4;
const {db} = require("../../config/dbconfig");
const crypto = require('crypto');
const {generateToken} = require("../../utils/JWT");
const jwt = require("jsonwebtoken");

const SM4_KEY = "1024lab__1024lab"
// 定义一个密钥，用于签名 Token
const JWT_SECRET = '1024lab__1024lab'; // 确保将其保存在安全的地方
// 存储验证码及其过期时间
const captchaStore = {};
const CAPTCHA_EXPIRY_TIME = 60; // 5分钟
const captchaKey = crypto.randomBytes(16).toString('hex');
exports.getCaptcha = async (req, res) => {
    const captcha = svgCaptcha.create({
        size: 4,
        ignoreChars: '0o1l',
        width: 100,
        height: 40,
        fontSize: 50,
        noise: 3,
    });

// 生成一个唯一的key来存储验证码

    captchaStore[captchaKey] = {
        text: captcha.text,
        expiry: Date.now() + CAPTCHA_EXPIRY_TIME * 1000
    };
    // 将验证码图片编码为base64格式
    const base64Image = Buffer.from(captcha.data).toString('base64');
    console.log(captcha.text)
    res.json({
        code: 1,
        data: {
            captchaUuid: Math.random().toString(36).substring(7),
            captcha: captcha.text,
            captchaBase64Image: `data:image/svg+xml;base64,${base64Image}`,
            expireSeconds: Date.now() + CAPTCHA_EXPIRY_TIME * 1000
        }
    });
}

function onLoginCheckCaptcha(captchaCode) {
    console.log(captchaCode, captchaStore)
    const captchaEntry = captchaStore[captchaKey];

    // 检查验证码是否存在
    if (!captchaEntry) {
        console.log('验证码不存在');
        return false; // 验证码不存在
    }

    // 检查验证码是否过期
    if (Date.now() > captchaEntry.expiry) {
        console.log('验证码已过期');
        delete captchaStore[captchaKey]; // 删除过期的验证码
        return false; // 验证码已过期
    }

    // 检查输入的验证码是否正确
    if (captchaEntry.text !== captchaCode) {
        console.log('验证码不正确');
        return false; // 验证码不正确
    }

    // 验证成功后删除验证码
    delete captchaStore[captchaKey];
    console.log('验证码验证成功');
    return true; // 验证成功
}

exports.checkCaptcha = (req, res) => {
    const {captchaCode} = req.body;

    // 检查验证码是否存在和是否过期
    const expiryTime = captchaStore[captchaCode];
    if (expiryTime && Date.now() < expiryTime) {
        delete captchaStore[captchaCode]; // 验证后删除
        return res.json({valid: true, message: '验证码正确'});
    } else {
        return res.json({valid: false, message: '验证码无效或已过期'});
    }
}

exports.onLogin = async (req, res) => {
    const {loginName, password, captchaCode, captchaUuid, loginDevice} = req.body;
    // 1. 验证输入
    if (!loginName || !password || !captchaCode) {
        return res.status(400).json({message: '缺少必要的字段'});
    }

    // 2. 验证验证码
    const isCaptchaValid = onLoginCheckCaptcha(captchaCode);
    console.log(isCaptchaValid)
    if (!isCaptchaValid) {
        return res.json({code: 0, data: {message: '验证码不正确'}});
    }

    // 3. 查找用户（假设有个用户模型）
    async function findUser(loginName) {
        const sql = `SELECT * FROM users WHERE username = '${loginName}'`;
        return new Promise((resolve, reject) => {
            db.query(sql, (err, result) => {
                if (err) {
                    return reject(err); // 如果出错，拒绝 Promise
                }
                resolve(result[0]); // 成功时解析 Promise
            })
        })
    }

    const user = await findUser(loginName);
    if (!user) {
        return res.json({code: 0, data: {message: '用户名或密码错误'}});
    }

    function decryptSM4(encryptedData) {
        const keyHex = Buffer.from(SM4_KEY, 'utf8').toString('hex'); // SM4 密钥
        const base64DecodedData = Buffer.from(encryptedData, 'base64').toString('utf8');

        return sm4.decrypt(base64DecodedData, keyHex);
    }

    // 4. 验证密码
    const isPasswordValid = user.password === decryptSM4(password)
    if (!isPasswordValid) {
        return res.json({code: 0, data: {message: '用户名或密码错误'}});
    }


    // 5. 登录成功，生成 Token（假设有个生成 Token 的函数）
    const token = generateToken(user, loginDevice);

    // 6. 返回成功响应
    return res.status(200).json({code: 1, data: {message: '登录成功', token, user}});
}

exports.checkToken = (req, res) => {
    const token = req.headers['authorization']; // 从请求头中获取 Token
    if (!token) {
        return res.cc({code: 0, message: '没有提供 Token'});
    }
    jwt.verify(token, JWT_SECRET, (err, decoded) => {
        if (err) {
            return res.cc({code: 0, message: '无效的 Token'});
        }
    });
}